<template>
    <div>
        <!-- 头部 -->
        <header class="w-34 py-5 w-full flex items-center justify-between">
            <aside class="w-1/2 flex items-center">
                <n-button type="success" class="mr-2" @click="addAdmin">添加</n-button>
                <n-input placeholder="关键字搜索" style="width: 20rem" v-model:value="keyword">
                    <template #prefix>
                        <n-icon :component="FlashOutline" />
                    </template>
             </n-input>
             <n-button class="ml-2" type="primary" @click="SearchList">搜索</n-button>
            </aside>
        </header>
        <!-- 表格 -->
        <n-data-table
            striped 
            ref="tableRef"
            :columns="columns"
            :data="adminList"
            :bordered="true"
            :pagination="paginationReactive"
        />
    </div>

    <!-- 添加管理员 -->
    <n-modal
        v-model:show="showModal"
        preset="card"
        title="添加项目负责人"
        :style="{width: '400px'}"
  >
  <n-form ref="formRef" :model="model" :rules="rules">
    <n-form-item path="username" label="姓名">
      <n-input v-model:value="model.username" @keydown.enter.prevent placeholder="请输入姓名" />
    </n-form-item>
    <n-form-item path="phone" label="手机号">
      <n-input
        v-model:value="model.phone"
        type="text"
        placeholder="请输入手机号"
        @keydown.enter.prevent
      />
    </n-form-item>
    <n-form-item class="flex justify-end">
        <n-button class="mr-2" @click="onNegativeClick">取消</n-button>
        <n-button type="success" @click="onconfirmClick">确认</n-button>
    </n-form-item>
    </n-form>
  </n-modal>

     <!-- 修改管理员 -->
     <n-modal
        v-model:show="updateModal"
        preset="card"
        title="修改项目负责人"
        :style="{width: '400px'}"
  >
  <n-form ref="updateformRef" :model="updateModalForm" :rules="updaterules">
    <n-form-item path="id" label="编号">
        <n-input v-model:value="updateModalForm.id"></n-input>
    </n-form-item>
    <n-form-item path="admin_username" label="姓名">
      <n-input v-model:value="updateModalForm.admin_username" @keydown.enter.prevent placeholder="请输入姓名" />
    </n-form-item>
    <n-form-item path="phone" label="手机号">
      <n-input
        disabled
        v-model:value="updateModalForm.phone"
        type="text"
        placeholder="请输入手机号"
        @keydown.enter.prevent
      />
    </n-form-item>
    <n-form-item class="flex justify-end">
        <n-button class="mr-2" @click="onCancel">取消</n-button>
        <n-button type="success" @click="onupdateonfirmClick">确认</n-button>
    </n-form-item>
    </n-form>
  </n-modal>

</template>

<script setup lang="ts">
    import dayjs from 'dayjs'
    import { Create } from '@vicons/ionicons5';
    import Papa from 'papaparse';
    import { FormRules, NButton, NIcon,NPopconfirm, NTag } from 'naive-ui';
    import { getCurrentInstance } from 'vue';
    import { Globe,Backspace } from '@vicons/ionicons5'
    import { ref,onMounted,reactive } from 'vue'
    let { proxy } = getCurrentInstance()
    let adminList = ref([]) //新闻列表
    let showModal = ref(false)
    import { NewAdmin, updateAdminInfo, deleteAdmin } from '../../Api/admin/index'
    /**
     * 添加管理员
     */
    let formRef = ref()
    const addAdmin = () => {
        showModal.value = true
    }
    // 确认添加
    const onconfirmClick = () => {
        formRef.value.validate(async (valid: any) => {
            if (valid) return proxy.$message.error('请按照要求添加信息')
            // 填写成功
            let result = await NewAdmin(model.username,model.phone)
            if (result.data.code !== 200) return proxy.$message.error(result.data.msg)
            proxy.$message.success('添加成功')
            showModal.value = false
            getNewsList()
        }).catch((err: any) => {
            console.log(err)
        })
    }

    // 取消添加
    const onNegativeClick = () => {
        showModal.value = false
        formRef.value.restoreValidation()
        model.phone = ''
        model.username = ''
    }

    // 验证规则
    const updaterules: FormRules = {
        admin_username: [{
            required: true,
            trigger: ['input', 'blur'],
            validator(rule: any,value: string) {
                if (!value) {
                    return new Error('用户名不能为空')
                } else {
                    return true
                }
            }
        }],
        phone:[{
            required: true,
            trigger: ['input', 'blur'],
            validator(rule: any,value: string) {
                if (!value) return new Error('手机号不能为空')
                else if (!(/^1[3-9]\d{9}$/.test(value))) {
                    return new Error('手机格式错误')
                }
                return true
            }
        }],
        id: [
            {
                required: true,
                trigger: ['input', 'blur'],
                validator(rule: any,value: string) {
                    if (!value) return new Error('id不能为空')
                    if (!(/^\d{1,}$/.test(value))) {
                        return new Error('id格式错误')
                    }
                    return true
                }
            }
        ]
    }
    const rules: FormRules = {
        username: [{
            required: true,
            trigger: ['input', 'blur'],
            validator(rule: any,value: string) {
                if (!value) {
                    return new Error('用户名不能为空')
                } else {
                    return true
                }
            }
        }],
        phone:[{
            required: true,
            trigger: ['input', 'blur'],
            validator(rule: any,value: string) {
                if (!value) return new Error('手机号不能为空')
                else if (!(/^1[3-9]\d{9}$/.test(value))) {
                    return new Error('手机格式错误')
                }
                return true
            }
        }]
    }
    const model = reactive({
        username: '',
        phone: ''
    })

    // 修改参数
    const updateModal = ref(false)
    const updateformRef = ref()
    const updateModalForm = reactive<Record<string,any>>({
        admin_username: '',
        phone: '',
        id: ''
    })
    const onCancel = () => {
        updateModal.value = false
        updateformRef.value.restoreValidation()
    }
    // 确认修改
    const onupdateonfirmClick = () => {
        updateformRef.value.validate(async (valid: boolean) => {
            if (valid) return proxy.$message.error('请按照要求添加信息')
            // 填写成功
            let result = await updateAdminInfo(updateModalForm.id,updateModalForm.admin_username,updateModalForm.phone)
            if (result.data.code !== 200) return proxy.$message.error(result.data.msg)
            proxy.$message.success('修改成功')
            updateModal.value = false
            getNewsList()
        }).catch((err: any) => {
            console.log(err)
        })
    }
    // 生命周期
    onMounted(()=>{
        getNewsList()
    })
    /**
     * 数据渲染
     */
    let tableRef = ref()
    const columns = [
        {
            title: '编号',
            key: 'id',
            width: '5%',
            align: 'center'
        },
        { 
            title: '项目负责人', 
            key: 'admin_username',
            width: '10%',
            align: 'center',
            render: (row: Record<string,any>) => {
                return h('div',{style: {color: '#e74c3c',fontWeight: 'bold'}},row.admin_username)
            }

         },
        { title: '手机号码', key: 'phone', width: '10%', align: 'center' },
        {
            title: '微信唯一标识',
            key: 'openid',
            align: 'center',
            width: '30%'
        },
        {
            title: '创建时间',
            key: 'createdAt',
            align: 'center',
            width: '15%',
            render: (row) => {
                return h('div', {}, dayjs(row.createdAt).format('YYYY-MM-DD HH:mm:ss'))
            }
        },
        {
            title: '更新时间',
            key: 'updatedAt',
            align: 'center',
            width: '15%',
            render: (row) => {
                return h('div', {}, dayjs(row.updatedAt).format('YYYY-MM-DD HH:mm:ss'))
            }
        },
        { title: '操作', key: 'action', width: '240px', align: 'center',render(row) {
            return h('div', 
            {
                style: { display: 'flex', justifyContent: 'center' }
            },
            [
            h(NButton, {
                    type: 'info',
                    size: 'small',
                    onClick:() => {
                     updateModal.value = true
                     updateModalForm.admin_username = row.admin_username
                     updateModalForm.phone = row.phone
                     updateModalForm.id = row.id     
                    },
                    style: {
                        marginRight: '10px'
                    },
                },
                {
                    default: () => h('div',{style: {display: 'flex',alignItems: 'center'}},[
                        h(NIcon,{size:16,component: Create,color: '#fff'}),
                        h('span',{style: {marginLeft: '5px'}},'编辑')
                    ])
                }),
                h(NPopconfirm,{
                        onPositiveClick: async () => {
                        let id:number = row.id // 用户留言编号
                        let result = await deleteAdmin(id)
                        if (result.data.code !== 200) return proxy.$message.error("删除失败")
                        proxy.$message.success("删除成功")
                        getNewsList()
                    },
                    onNegativeClick: () => {
                        proxy.$message.info("取消删除")
                    }
                },{
              trigger: () => h(NButton,{ type: 'error',size: 'small'},[
                h(NIcon,{size:16,component: Backspace,color: '#fff'}),
                h('span',{style: {marginLeft: '5px'}},'删除')
            ]),
              default: () => h(
              'div', 
              '确定删除吗？',
            )
            })
         ])
        }}
    ]
    let keyword = ref('')
    
    const SearchList = () => {
        tableRef.value.filter({
            zh_title: [keyword.value],
        })
    }
    // 获取新闻列表
    const getNewsList = async () => {
        let res = await proxy.$http.get("/weixin/getAdminList")
        adminList.value = res.data.data
    }

    // 确认删除
    const handlePositiveClick = async (id: number) => {
        let res = await proxy.$http.delete(`/weixin/deleteProject/${id}`)
        if(res.data.code === 200){
            proxy.$message.success("删除成功")
            getNewsList()
        }
    }
    // 取消删除
    const handleNegativeClick = () => {
        proxy.$message.info("已取消删除")
    }


    /**
     * 分页操作
     */
     const paginationReactive = reactive({
      page: 1,
      pageSize: 5,
      showSizePicker: true,
      pageSizes: [5, 10, 15],
      onChange: (page: number) => {
        paginationReactive.page = page
      },
      onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
      }
    })
    const pageCount = ref(3)
    const page = ref(1)
    const pageSize = ref(5)
    const pageSizes = [
        {
            label: "5 每页",
            value: 10
        },
        {
            label: "10 每页",
            value: 15
        }
    ]
    import {FlashOutline} from '@vicons/ionicons5'
    import { h } from 'vue';

</script>

<style lang="less" scoped>
    :deep(.n-data-table__pagination) {
        display: flex;
        justify-content: center;
    }
    :deep(.n-drawer-header__main) {
        width: 100%!important;
    }
    :deep(.MsoNormal) {
        display: flex;
        justify-content: center;
    }
    :deep(.n-pagination) {
        display: flex;
        justify-content: center;
    }
</style>